import 'package:ball_lion/module/pick/items/avator_label.dart';
import 'package:ball_lion/module/pick/items/expert_record_tag.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/expert/plan_pack/plan_pack_detail_logic.dart';
import 'package:ball_lion/entity/expert/plan_pack/plan_pack_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/widget/history_label.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/entity/match/expert_views_entity.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/widgets/asset_item.dart';

class PlanPackDetailPage extends StatefulWidget {
  const PlanPackDetailPage({super.key});

  @override
  State<PlanPackDetailPage> createState() => _PlanPackDetailPageState();
}

class _PlanPackDetailPageState extends State<PlanPackDetailPage> {
  final PlanPackDetailLogic logic =
      Get.put(PlanPackDetailLogic(), tag: "${Get.arguments}");

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PlanPackDetailLogic>(
        tag: "${Get.arguments}",
        builder: (logic) {
          return Scaffold(
            backgroundColor: Colours.greyF2F3F7,
            appBar: Styles.appBar(title: const QsText("套餐详情")),
            body: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: [info(), content(), Container(height: 50)],
                    ),
                  ),
                ),
                if (logic.data?.showPay ?? true) payBar()
              ],
            ),
          );
        });
  }

  Widget info() {
    return Block(
        cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
            padding: EdgeInsets.all(12)),
        child: Column(
          children: [
            QsText(logic.data?.title ?? "",
                maxLines: 99, fontSize: 22, fontWeight: FontWeight.w500),
            const Divider(height: 0.5, color: Colours.greyEE)
                .paddingSymmetric(vertical: 12),
            AvatarLabel.record(
              avatarUrl: logic.data?.expertLogo,
              name: logic.data?.expertName,
              id: logic.data?.expertId,
              firstTag: logic.data?.tag,
              nameWeight: FontWeight.w500,
            ),
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () => Get.toNamed(Routes.planPackHistory,
                  arguments: logic.data?.expertId),
              child: Row(
                children: [
                  const QsText("历史战绩：",
                      fontWeight: FontWeight.w500, needCenter: true),
                  Expanded(
                      child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: logic.data?.historyTag.noValue ?? true
                        ? const QsText("暂无历史战绩",
                            fontSize: 12, color: Colours.grey99)
                        : Row(
                            children: List.generate(
                                logic.data?.historyTag?.length ?? 0,
                                (index) => Container(
                                    margin: const EdgeInsets.only(right: 4),
                                    alignment: Alignment.center,
                                    height: 14,
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 4),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(2),
                                        border: Border.all(
                                            color: Colours.main, width: 0.5)),
                                    child: QsText(
                                        logic.data!.historyTag![index],
                                        fontSize: 10,
                                        color: Colours.main,
                                        needCenter: true)))),
                  )),
                  const AssetItem(
                    asset: 'arrow_right_36.png',
                    name: '点此查看',
                    assetSize: 12,
                    space: 2,
                    direction: AssetDirection.rtl,
                    textStyle: TextStyle(color: Colours.grey99, fontSize: 12),
                  )
                ],
              ),
            ).paddingOnly(top: 12)
          ],
        ));
  }

  Widget content() {
    String line = '';
    if (logic.data?.plans.hasValue ?? false) {
      line =
          "总计${logic.data?.total ?? 0}场，已发布${logic.data?.plans?.length ?? 0}场";
    } else {
      line = "套餐总计${logic.data?.total ?? 0}场比赛\n内容即将发布，请稍后刷新查看";
    }
    return Block(
        cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 16)),
        child: Column(
          children: [
            QsText(
              logic.data?.content ?? "",
              fontSize: 16,
              maxLines: 99,
            ),
            Row(
              children: [
                Expanded(
                    child: Container(
                  height: 0.5,
                  color: Colours.main,
                )),
                Row(
                  children: [
                    QsText(line,
                        color: Colours.main,
                        fontSize: 12,
                        textAlign: TextAlign.center),
                    if (logic.data?.plans?.length == logic.data?.total)
                      ExpertRecordTag.custom(
                              text: logic.data?.packageTag,
                              textSize: 10,
                              radius: 2,
                              tagType: TagType(
                                  borderColor: Colours.main,
                                  textColor: Colours.main))
                          .paddingOnly(left: 6)
                  ],
                ).marginSymmetric(horizontal: 10),
                Expanded(
                    child: Container(
                  height: 0.5,
                  color: Colours.main,
                )),
              ],
            ).marginOnly(top: 16, bottom: 8),
            ...logic.data?.plans?.map((e) => item(e)).toList() ?? []
          ],
        ));
  }

  Widget payBar() {
    return Column(
      children: [
        if (logic.data?.status == PlanPackStatus.close) ...[
          const Divider(color: Colours.greyEE, height: 0.5),
          Container(
            height: 28,
            color: Colours.white,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                Image.asset(width: 15, Utils.getImgPath("planinfo_alert.png")),
                const SizedBox(width: 5),
                const QsText("方案所含比赛已开始，当前不可付费阅读！",
                    fontSize: 12, color: Colours.main)
              ],
            ),
          ),
        ],
        const Divider(color: Colours.greyEE, height: 0.5),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          color: Colours.white,
          child: DefaultTextStyle(
            style: const TextStyle(fontSize: 12, color: Colours.grey99),
            child: Row(children: [
              const QsText('套餐价:'),
              Container(width: 4),
              QsText(logic.data?.price ?? "",
                  color: Colours.main, fontSize: 16),
              Container(width: 2),
              QsText("球币".changeUnit, color: Colours.main),
              Container(width: 4),
              QsText("原价：${logic.data?.oldPrice}球币".changeUnit,
                  decoration: TextDecoration.lineThrough),
              const Spacer(),
              QsButton(
                  enable: logic.data?.status == PlanPackStatus.sale,
                  width: 108,
                  height: 40,
                  onPressed: logic.toPay,
                  text: "立即支付",
                  textStyle: const TextStyle(fontSize: 16),
                  backgroundColor: Colours.main,
                  foregroundColor: Colours.white)
            ]),
          ),
        ),
      ],
    );
  }

  Widget item(PlanEntity entity) {
    MatchBries? match;
    if (entity.matchBries?.hasValue ?? false) match = entity.matchBries?.first;
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => Get.toNamed(Routes.viewpoint, arguments: entity.planId),
      child: Stack(
        alignment: AlignmentDirectional.topEnd,
        children: [
          Block(
            cardStyle: const CardStyle(
                margin: EdgeInsets.only(top: 8),
                padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
                color: Colours.blueF7FAFF,
                radius: 6),
            child: Column(
              children: [
                entityTop(match),
                middle(match).paddingSymmetric(vertical: 8),
                const Divider(color: Colours.greyDD, height: 0.5),
                Row(
                  children: [
                    QsText("[${entity.playTypeName ?? ""}]",
                        color: Colours.blue39407E, fontSize: 12),
                    Container(width: 4),
                    QsText(
                        "发布时间：${DateTime.tryParse(entity.planPublicTime ?? "")?.formatedString('yyyy/MM/dd HH:mm')}",
                        fontSize: 12,
                        color: Colours.grey66)
                  ],
                ).paddingSymmetric(vertical: 8)
              ],
            ),
          ),
          HistoryLabel.viewpoint(
              state: entity.planStatus, width: 36, fontSize: 14)
        ],
      ),
    );
  }

  Widget entityTop(MatchBries? entity) {
    return DefaultTextStyle(
      style: const TextStyle(color: Colours.grey66, fontSize: 11),
      child: GestureDetector(
        onTap: () =>
            Get.toNamed(Routes.leagueDetail, arguments: "${entity?.leagueId}"),
        child: Row(
          children: [
            QsText(entity?.leagueName ?? "", needCenter: true),
            Container(width: 6),
            QsText(
              DateTime.tryParse(entity?.matchTime ?? "")
                  ?.formatedString("MM-dd HH:mm"),
              height: 1.2,
            ),
            Container(width: 6),
            QsText(entity?.jcMatchNo ?? ""),
          ],
        ),
      ),
    );
  }

  Widget middle(MatchBries? entity) {
    return Row(
      children: [
        Expanded(
            flex: 3,
            child: teamInfo(entity?.homeLogo, entity?.homeName,
                entity?.homeRanking, false)),
        Expanded(flex: 1, child: score(entity).center),
        Expanded(
            flex: 3,
            child: teamInfo(entity?.guestLogo, entity?.guestName,
                entity?.guestRanking, true))
      ],
    );
  }

  Widget teamInfo(String? logo, String? name, String? rank, bool reverse) {
    List<Widget> info = [
      CachedNetworkImage(
          width: 28,
          height: 28,
          placeholder: (context, url) => Styles.placeholderIcon(),
          errorWidget: (
            context,
            url,
            error,
          ) =>
              Image.asset(Utils.getImgPath("zq_placeholder.png")),
          imageUrl: logo ?? ""),
      Container(width: 8),
      Flexible(
        child: QsText(name ?? "",
            fontWeight: FontWeight.w500,
            fontSize: 14,
            maxLines: 1,
            textAlign: reverse ? TextAlign.end : TextAlign.start),
      ),
      Container(width: 2),
      if (rank.hasValue) QsText("[$rank]", fontSize: 11, color: Colours.grey99)
    ];
    return Row(
        mainAxisAlignment:
            reverse ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: reverse ? info.reversed.toList() : info);
  }

  Widget score(MatchBries? entity) {
    String result = "";
    switch (entity?.status) {
      case 7:
        result = '${entity?.homeScore90}-${entity?.guestScore90}';
        break;
      case 8:
        result = "取消";
        break;
      case 9:
        result = "中断";
        break;
      case 10:
        result = "腰斩";
        break;
      case 11:
        result = "延期";
        break;
      case 12:
        result = "待定";
        break;
      default:
        result = "vs";
    }
    return DefaultTextStyle(
      style: const TextStyle(
          fontSize: 14, fontWeight: FontWeight.w500, color: Colours.grey66),
      child: QsText(result),
    );
  }
}
